Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: guard log volume in CI so it cannot regress unnoticed (#9665)
Daniel Hancd041a04c419
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.ymlindex 3adba96bb6a..a6dc6f5c00d 100644--- a/.github/workflows/studio-ui-smoke.yml+++ b/.github/workflows/studio-ui-smoke.yml@@ -634,6 +634,26 @@ jobs:mkdir -p logs/playwright_image_cancel_retry_coldpython tests/studio/playwright_image_download_cancel_retry.py+ # The log budget in studio/backend/tests/log_budget compares two BACKEND files with+ # each other: the suppression sets in loggers/handlers.py and the poll cadences in+ # session.py. A pull request that adds a polling call site in the frontend edits+ # neither, so it passes, and the new endpoint logs every hit on a 300 ms window.+ # Only a browser can see that a timer started, whatever it was implemented with.+ #+ # Last of the shard's steps on purpose: it walks the sidebar and then sits idle for+ # two minutes, and it rotates the bootstrap password, so anything scheduled after it+ # would wait on the dwell and then meet a password it did not mint.+ - name: Every polled path is declared in the log budget (Playwright)+ if: matrix.shard == 'extra'+ env:+ BASE_URL: http://127.0.0.1:18894+ STUDIO_OLD_PW: ${{ env.STUDIO_EXTRA_OLD_PW }}+ STUDIO_NEW_PW: ${{ env.STUDIO_EXTRA_NEW_PW }}+ PW_ART_DIR: logs/playwright_declared_polls+ run: |+ mkdir -p logs/playwright_declared_polls+ python tests/studio/playwright_declared_polls.py+- name: Stop second Unslothif: (always()) && (matrix.shard == 'extra' || matrix.shard == 'banner')run: |diff --git a/studio/backend/tests/fixtures/access_log_records.json b/studio/backend/tests/fixtures/access_log_records.jsonnew file mode 100644index 00000000000..77aa4a7661f--- /dev/null+++ b/studio/backend/tests/fixtures/access_log_records.json@@ -0,0 +1,103 @@+{+ "_comment": [+ "One definition of 'a successful access record', consumed by both languages.",+ "",+ "The desktop shell decides whether to mirror a backend stdout line into tauri.log,",+ "and the backend decides whether to emit it at all. Those are two implementations of",+ "the same idea in two languages and two processes, so they can drift; the CRLF",+ "handling in the progress-frame collapsers already did drift once.",+ "",+ "Python reads this from tests/test_log_rule_parity.py. Rust reads it from the",+ "shared_access_log_fixture_tests module in src-tauri/src/process.rs. A change to the",+ "rule on one side turns the other side red.",+ "",+ "keep=false means the line is a successful access record that tauri.log may drop",+ "because it is already on the phase log and the backend session log."+ ],+ "cases": [+ {+ "name": "plain 200 access record",+ "line": "{\"event\": \"request_completed\", \"method\": \"GET\", \"path\": \"/api/health\", \"status_code\": 200}",+ "keep": false,+ "why": "the duplicated line this whole mechanism exists to drop"+ },+ {+ "name": "299 is still success",+ "line": "{\"event\": \"request_completed\", \"method\": \"GET\", \"path\": \"/api/health\", \"status_code\": 299}",+ "keep": false,+ "why": "upper edge of the 2xx range"+ },+ {+ "name": "199 is not success",+ "line": "{\"event\": \"request_completed\", \"method\": \"GET\", \"path\": \"/api/health\", \"status_code\": 199}",+ "keep": true,+ "why": "lower edge; anything outside 2xx keeps its line"+ },+ {+ "name": "300 is not success",+ "line": "{\"event\": \"request_completed\", \"method\": \"GET\", \"path\": \"/api/health\", \"status_code\": 300}",+ "keep": true,+ "why": "a redirect is not a success and must stay visible"+ },+ {+ "name": "404 failure",+ "line": "{\"event\": \"request_completed\", \"method\": \"GET\", \"path\": \"/api/nope\", \"status_code\": 404}",+ "keep": true,+ "why": "the line a support engineer is looking for"+ },+ {+ "name": "500 failure",+ "line": "{\"event\": \"request_completed\", \"method\": \"POST\", \"path\": \"/api/inference/load\", \"status_code\": 500}",+ "keep": true,+ "why": "server error"+ },+ {+ "name": "request_completed with no status_code",+ "line": "{\"event\": \"request_completed\", \"method\": \"GET\", \"path\": \"/api/health\"}",+ "keep": true,+ "why": "a record we cannot vouch for is kept rather than guessed at"+ },+ {+ "name": "status_code is a string",+ "line": "{\"event\": \"request_completed\", \"method\": \"GET\", \"path\": \"/api/health\", \"status_code\": \"200\"}",+ "keep": true,+ "why": "not an integer, so the success test does not apply"+ },+ {+ "name": "a different structured event",+ "line": "{\"event\": \"request_failed\", \"method\": \"GET\", \"path\": \"/api/health\", \"status_code\": 200}",+ "keep": true,+ "why": "only request_completed is an access record"+ },+ {+ "name": "hardware line, not JSON",+ "line": "Hardware detected: NVIDIA RTX 4090",+ "keep": true,+ "why": "plain text always survives"+ },+ {+ "name": "malformed JSON",+ "line": "{\"event\": \"request_completed\", \"status_code\": 200",+ "keep": true,+ "why": "unparseable, so it is not recognised as an access record"+ },+ {+ "name": "leading whitespace before the object",+ "line": " {\"event\": \"request_completed\", \"method\": \"GET\", \"path\": \"/api/health\", \"status_code\": 200}",+ "keep": false,+ "why": "both sides trim the start before parsing"+ },+ {+ "name": "empty line",+ "line": "",+ "keep": true,+ "why": "nothing to recognise"+ },+ {+ "name": "traceback frame",+ "line": " File \"run.py\", line 1, in <module>",+ "keep": true,+ "why": "tracebacks must never be filtered"+ }+ ]+}diff --git a/studio/backend/tests/log_budget/__init__.py b/studio/backend/tests/log_budget/__init__.pynew file mode 100644index 00000000000..2a2c396521d--- /dev/null+++ b/studio/backend/tests/log_budget/__init__.py@@ -0,0 +1,4 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Shared harness for the log-volume guards."""diff --git a/studio/backend/tests/log_budget/policy.py b/studio/backend/tests/log_budget/policy.pynew file mode 100644index 00000000000..c39bd297126--- /dev/null+++ b/studio/backend/tests/log_budget/policy.py@@ -0,0 +1,116 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Log policy classes, derived from the middleware rather than duplicated from it.++A per-path budget table would be a second copy of the suppression rules, and a second copy+drifts. The class of a path is therefore read out of ``loggers.handlers`` at run time; the+only thing checked in here is how often each path is POLLED, which is the one fact the+backend genuinely does not know.++Budgeting by class rather than by path is also what stops the numbers becoming a haggling+ledger: a new endpoint picks an existing class and no number changes at all.+"""++from __future__ import annotations++import math+from typing import Optional++NORMAL = "normal"+QUIET = "quiet"+LIVENESS = "liveness"+WATCHDOG = "watchdog"+QUIET_SUCCESS = "quiet_success"+EXCLUDED = "excluded"++ALL_CLASSES = (NORMAL, QUIET, LIVENESS, WATCHDOG, QUIET_SUCCESS, EXCLUDED)++# Classes whose 2xx traffic is dropped outright rather than heartbeated, so no window and+# no budget applies: the expected count is zero.+NEVER_LOGGED_ON_SUCCESS = (QUIET_SUCCESS, EXCLUDED)+++def watchdog_paths(handlers) -> frozenset:+ """The watchdog set, absent until the liveness-heartbeat change lands.++ Read through ``getattr`` so this harness works on both sides of that merge instead of+ pinning the guard to one revision.+ """+ return frozenset(getattr(handlers, "_WATCHDOG_POLL_PATHS", frozenset()))+++def classify(handlers, path: str) -> str:+ """Which suppression rule owns ``path``. Most specific first.++ Order matters: the liveness paths are a subset of the quiet paths, and the watchdog set+ is deliberately outside the quiet set because its window is wider.+ """+ if path in handlers._EXCLUDED_PATHS or path.endswith(handlers._EXCLUDED_SUFFIXES):+ return EXCLUDED+ if path.startswith("/assets/"):+ return EXCLUDED+ # _CHAT_LIST_PATHS rides the same suppressor as _QUIET_SUCCESS_PATHS in+ # `_is_quiet_success`, so it is the same class even though it is a separate set (it+ # carries a second rule about pre-auth 401s that the others do not).+ if (+ path in handlers._QUIET_SUCCESS_PATHS+ or path in handlers._SELF_READ_PATHS+ or path in handlers._CHAT_LIST_PATHS+ ):+ return QUIET_SUCCESS+ if path in watchdog_paths(handlers):+ return WATCHDOG+ if path in handlers._LIVENESS_POLL_PATHS:+ return LIVENESS+ if path in handlers._QUIET_POLL_PATHS:+ return QUIET+ return NORMAL+++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+ if cls == WATCHDOG:+ return getattr(handlers, "_WATCHDOG_POLL_DEDUP_MS", handlers._QUIET_POLL_DEDUP_MS)+ if cls in (QUIET, LIVENESS):+ return handlers._QUIET_POLL_DEDUP_MS+ return handlers._ACCESS_LOG_DEDUP_MS+++def expected_emissions(window_ms_value: Optional[int], period_s: float, duration_s: float) -> int:+ """How many lines a periodic poll SHOULD produce. A formula, not a snapshot.++ The middleware stamps only when it emits, so the gap between two emitted lines is the+ smallest whole number of polls that spans the window. With ``n`` polls in the run and+ ``k`` polls per emission, that is ``(n - 1) // k + 1``.++ Deriving this rather than recording a measured number is what makes the guard survive a+ change to a poll interval: widen the window and the expectation moves with it, so only+ a genuine regression fails.+ """+ if window_ms_value is None:+ return 0+ if period_s <= 0:+ raise ValueError("period must be positive")+ polls = math.ceil(duration_s / period_s)+ if polls <= 0:+ return 0+ if window_ms_value <= 0:+ return polls # window off (--verbose): every poll logs+ polls_per_emission = max(1, math.ceil((window_ms_value / 1000.0) / period_s))+ return (polls - 1) // polls_per_emission + 1+++def bucket_of(handlers, path: str) -> str:+ """The de-duplication bucket a path competes in.++ The liveness paths deliberately SHARE one bucket: the SPA fires all of them together+ and they all answer the same question, so the first of the burst logs with its real+ path and the rest of that window is dropped. Budgeting them per path would expect five+ lines where the design intends one, so the guard has to budget the bucket.+ """+ if classify(handlers, path) == LIVENESS:+ return "\x00liveness"+ return pathdiff --git a/studio/backend/tests/log_budget/replay.py b/studio/backend/tests/log_budget/replay.pynew file mode 100644index 00000000000..187d0e6fba3--- /dev/null+++ b/studio/backend/tests/log_budget/replay.py@@ -0,0 +1,195 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Replay a Studio session through the real middleware in virtual time.++No sleeping and no wall clock. The middleware takes its timestamps from+``time.perf_counter`` in its own module namespace, so swapping that namespace for a clock+the test advances by hand makes a thirty-minute session run instantly and identically on a+loaded CI runner. Real sleeps would put every assertion within scheduler noise of a window+boundary, which is how a guard like this becomes flaky and then gets deleted.++The middleware itself is real. So is the dedup state, the quiet-success suppressor and the+shared liveness bucket. Only the clock and the terminal application are substituted.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass, field+from typing import Optional+++class FakeClock:+ """Stands in for the ``time`` module inside ``loggers.handlers``.++ Only ``perf_counter`` is used by the middleware; anything else raises rather than+ silently falling through to the real module, so a future call site that starts reading+ the wall clock shows up here instead of quietly reintroducing nondeterminism.+ """++ def __init__(self, start: float = 1000.0) -> None:+ self.now = start++ def perf_counter(self) -> float:+ return self.now++ def advance(self, seconds: float) -> None:+ self.now += seconds++ def __getattr__(self, name: str):+ raise AttributeError(+ f"loggers.handlers called time.{name}(), which the log-budget replay does not "+ f"model. Add it to FakeClock deliberately rather than letting the guard fall "+ f"back to the wall clock."+ )+++class LogCapture:+ """Collects what the middleware logged, in order."""++ def __init__(self) -> None:+ self.events: list[tuple[str, str, dict]] = []++ def info(self, event, **kw):+ self.events.append(("info", event, kw))++ def error(self, event, **kw):+ self.events.append(("error", event, kw))++ def warning(self, event, **kw):+ self.events.append(("warning", event, kw))++ def paths(self) -> list[str]:+ return [kw["path"] for _lvl, ev, kw in self.events if "path" in kw]++ def records_for(self, path: str) -> list[dict]:+ return [kw for _lvl, _ev, kw in self.events if kw.get("path") == path]+++@dataclass+class Request:+ method: str+ path: str+ status: int = 200+ query: bytes = b""+ # How long the handler takes. Zero by default, which is what every scenario written+ # before this field wanted: a request that costs no virtual time. It exists because+ # the suppressors key on the STATUS CODE and never on the duration, so "a 200 that+ # took a minute" is a case the harness could not express at all, and therefore could+ # not budget or defend.+ duration_ms: float = 0.0+++@dataclass+class ReplayResult:+ capture: LogCapture+ sent: list[Request] = field(default_factory = list)++ @property+ def emitted(self) -> int:+ return len(self.capture.events)+++def _app_returning(+ status: int,+ duration_ms: float = 0.0,+ clock: "FakeClock | None" = None,+):+ async def app(scope, receive, send):+ # Advance BEFORE responding: the middleware stamps its window on the end time, so+ # a duration added afterwards would be invisible to the very rule under test.+ if duration_ms and clock is not None:+ clock.advance(duration_ms / 1000.0)+ await send({"type": "http.response.start", "status": status, "headers": []})+ await send({"type": "http.response.body", "body": b"ok"})++ return app+++async def _noop_receive():+ return {"type": "http.disconnect"}+++async def _noop_send(message):+ return None+++def install(+ handlers,+ monkeypatch,+ clock: Optional[FakeClock] = None,+) -> FakeClock:+ """Point the middleware at a virtual clock. Returns the clock."""+ clock = clock or FakeClock()+ monkeypatch.setattr(handlers, "time", clock)+ return clock+++def replay(+ handlers,+ monkeypatch,+ polled: dict,+ duration_s: float,+ boot: tuple = (),+ clock: Optional[FakeClock] = None,+ durations: Optional[dict] = None,+) -> ReplayResult:+ """Drive one middleware instance through ``boot`` then ``duration_s`` of polling.++ One instance for the whole run, because the de-duplication state lives on the instance+ and a fresh one per request would suppress nothing and quietly pass every budget.+ """+ from loggers.handlers import LoggingMiddleware++ clock = install(handlers, monkeypatch, clock)+ capture = LogCapture()+ monkeypatch.setattr(handlers, "logger", capture)++ middleware_by_status: dict[tuple[int, float], object] = {}+ result = ReplayResult(capture = capture)++ # A single middleware object shared by every status, so its dedup map is the real one.+ shared_state = LoggingMiddleware(_app_returning(200))++ def send_request(request: Request) -> None:+ key = (request.status, request.duration_ms)+ app = middleware_by_status.get(key)+ if app is None:+ app = _app_returning(request.status, request.duration_ms, clock)+ middleware_by_status[key] = app+ shared_state.app = app+ scope = {+ "type": "http",+ "path": request.path,+ "method": request.method,+ "query_string": request.query,+ }+ asyncio.run(shared_state(scope, _noop_receive, _noop_send))+ result.sent.append(request)++ for method, path, status in boot:+ send_request(Request(method = method, path = path, status = status))+ clock.advance(0.05)++ # Whole-second ticks, so every period in the registry lands on an exact tick and the+ # expectation formula and the replay agree by construction rather than by rounding.+ tick = 0.5+ started_at = clock.now+ next_due = {path: 0.0 for path in polled}+ while clock.now - started_at < duration_s:+ elapsed = clock.now - started_at+ for path, (period, _provenance) in polled.items():+ if elapsed + 1e-9 >= next_due[path]:+ send_request(+ Request(+ method = "GET",+ path = path,+ status = 200,+ duration_ms = durations.get(path, 0.0) if durations else 0.0,+ )+ )+ next_due[path] = elapsed + period+ clock.advance(tick)++ return resultdiff --git a/studio/backend/tests/log_budget/session.py b/studio/backend/tests/log_budget/session.pynew file mode 100644index 00000000000..32bf0739485--- /dev/null+++ b/studio/backend/tests/log_budget/session.py@@ -0,0 +1,148 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What an idle Studio actually asks for, and how often.++Every path the middleware classifies has to appear here with a poll period. That is the+whole mechanism: you cannot quiet a path without saying how often it is polled, and you+cannot start polling a path without classifying it. ``test_log_budget`` checks both+directions, so this file and ``loggers/handlers.py`` cannot drift apart silently.++Periods marked "measured" come from driving two real Studio instances for twelve minutes+and reading the access log back. The rest are the interval the UI declares at its call+site, and are marked "declared"; they are used identically by the replay and by the+expectation, so an imprecise one costs realism in the global envelope, never correctness of+a per-class check.+"""++from __future__ import annotations++# path -> (period_seconds, provenance)+#+# Polls that run when NOTHING is happening: the app is open and the user is not doing+# anything. This is the scenario the idle envelope is set against, and the one a new chatty+# endpoint will usually land in.+IDLE_POLLS: dict[str, tuple[float, str]] = {+ # The loaded-models indicator fires all four together for as long as the app is open.+ # This burst is what the shared liveness bucket exists to collapse.+ "/api/auth/status": (5.0, "measured"),+ "/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"),+ # Deliberately outside the shared bucket: their own latency is worth seeing, because+ # /api/health waits on hardware detection and /api/inference/status reads llama.cpp+ # capabilities.+ "/api/health": (5.0, "measured"),+ "/api/inference/status": (5.0, "measured"),+ # The desktop shell's watchdog probe: HEALTH_WATCHDOG_INTERVAL between rounds.+ "/api/liveness": (15.0, "measured"),+ # Re-read while the settings dialog or the remote-access section is open.+ "/api/settings/remote-access": (5.0, "measured"),+ # Tab lists, refetched on a timer and on every tab switch.+ "/api/train/runs": (20.0, "measured"),+ "/api/models/checkpoints": (20.0, "measured"),+ "/api/models/local": (20.0, "measured"),+ "/api/rag/knowledge-bases": (20.0, "measured"),+ # Chat lists, polled while the sidebar is open.+ "/api/chat/projects": (10.0, "declared"),+ "/api/chat/threads": (10.0, "declared"),+ # Small reads the shell and the settings pane make on a slow timer.+ "/api/llama/update-status": (5.0, "declared"),+ "/api/models/loras": (10.0, "declared"),+ "/api/providers/": (10.0, "declared"),+ "/api/providers/registry": (10.0, "declared"),+ "/api/settings/personalization": (10.0, "declared"),+ "/api/system": (10.0, "declared"),+}++# Polls that only exist while an operation is in flight: a download running, a generation+# running, a training run live, the log viewer open. Budgeted separately because holding+# all of them at once is not idle, and averaging them into the idle envelope would hide a+# regression in either direction.+BUSY_POLLS: dict[str, tuple[float, str]] = {+ "/api/models/download-progress": (1.0, "declared"),+ "/api/models/gguf-download-progress": (1.0, "declared"),+ "/api/datasets/download-progress": (1.0, "declared"),+ "/api/inference/images/generate-progress": (1.0, "declared"),+ "/api/inference/video/generate-progress": (1.0, "declared"),+ "/api/inference/images/load-progress": (1.0, "declared"),+ "/api/inference/video/load-progress": (1.0, "declared"),+ "/api/train/diffusion/status": (1.5, "declared"),+ # Suppressed entirely on success, but still polled, and still logged on failure.+ "/api/export/logs": (1.0, "declared"),+ "/api/export/status": (1.0, "declared"),+ "/api/hub/active-downloads": (1.0, "declared"),+ "/api/hub/datasets/active-downloads": (1.0, "declared"),+ "/api/hub/datasets/download-progress": (1.0, "declared"),+ "/api/hub/datasets/download-status": (1.0, "declared"),+ "/api/hub/datasets/transport-status": (1.0, "declared"),+ "/api/hub/download-progress": (1.0, "declared"),+ "/api/hub/download-status": (1.0, "declared"),+ "/api/hub/gguf-download-progress": (1.0, "declared"),+ "/api/hub/transport-status": (1.0, "declared"),+ "/api/inference/load-progress": (1.0, "declared"),+ # The log viewer reading its own log. Suppressed so that watching a log cannot append+ # to the log being watched.+ "/api/settings/debug/logs": (3.0, "declared"),+ "/api/settings/debug/logs/sources": (3.0, "declared"),+ # 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"),+}++# Every classified path lives in exactly one scenario. `test_log_budget` proves it.+ALL_POLLS: dict[str, tuple[float, str]] = {**IDLE_POLLS, **BUSY_POLLS}++STEADY_IDLE_SECONDS = 30 * 60+BUSY_SECONDS = 5 * 60++# Paths that are polled often and still sit in the `normal` burst class, so they write a+# line per poll. Introducing this guard to a codebase that already had violations means+# either recording them or weakening the rule, and weakening it would defeat the point.+#+# This list is self-expiring: `test_every_polled_path_has_exactly_one_class` fails if an+# entry here is NO LONGER a violation, so fixing one forces its removal and the list cannot+# quietly become permanent. Do not add to it to make a new endpoint pass.+#+# /api/settings/remote-access 360 lines per idle half hour -> fixed by #8763+# /api/liveness 120 lines per idle half hour -> fixed by #8763+# Empty, and worth keeping empty. #8763 gave both former entries a heartbeat class, and the+# closure test fails on a stale entry as loudly as on a missing one, so this cannot quietly+# become a place to park a chatty endpoint.+KNOWN_UNCLASSIFIED_POLLS: frozenset[str] = frozenset()++# The envelopes. These are what catch a NEW chatty endpoint: a path can satisfy its own+# class formula perfectly and still push the total up, which is exactly what happened to+# /api/liveness, whose 15s probe sat in the 300ms burst class and logged every single time.+#+# Raising either of these is a product decision about how much Studio is allowed to write.+# It is not a knob to turn because a test went red. The class formulas tell you whether the+# suppression rules are being honoured; these tell you whether the result is acceptable.+#+# Set from the measured behaviour of this revision plus room for a genuinely new endpoint,+# NOT from an aspiration.+#+# Ratcheted once already. Before #8763 idle measured 1380 and the envelope was 1450; the+# note here predicted the fix would take idle to roughly 930. It did not: idle now measures+# 1110. The prediction assumed /api/settings/remote-access would stop contributing, but a+# 10s heartbeat against a 5s poll still emits half of them, 180 lines over 30 minutes,+# which is now the joint-largest contributor. Left at 1450 the envelope would have had 340+# lines of slack, which is room for a whole new chatty endpoint to arrive unnoticed.+#+# Re-measure and ratchet again whenever a suppression rule changes. An envelope carrying+# the old number after a fix has stopped guarding anything.+STEADY_IDLE_LINE_ENVELOPE = 1170+BUSY_LINE_ENVELOPE = 260++# One-shot requests the app makes once on startup. Present so the boot window is not+# mistaken for steady state, and so a mutation record and a failure record exist to assert+# against.+BOOT_REQUESTS: tuple[tuple[str, str, int], ...] = (+ ("POST", "/api/auth/login", 200),+ ("GET", "/api/settings", 200),+ ("GET", "/api/models/list", 200),+ ("GET", "/api/chat/threads", 200),+ ("GET", "/api/inference/status", 401),+)diff --git a/studio/backend/tests/test_log_bounds.py b/studio/backend/tests/test_log_bounds.pynew file mode 100644index 00000000000..ca8b9f4d293--- /dev/null+++ b/studio/backend/tests/test_log_bounds.py@@ -0,0 +1,174 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Every log family must be bounded, and the two line caps must agree.++The volume guards cap how many lines get written. This one caps what is left on disk+afterwards, which is a separate failure: a family that writes one file per operation and+never prunes grows for the life of the install, and nothing in the line budget notices.++``utils.debug_log_sources.FAMILIES`` is the authoritative inventory of what Studio writes,+so it is the list a new family cannot avoid appearing on.+"""++from __future__ import annotations++import re+import sys+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from utils import debug_log_sources # noqa: E402++_STUDIO = Path(__file__).resolve().parents[2]+_MAIN_RS = _STUDIO / "src-tauri" / "src" / "main.rs"+_DIAGNOSTICS_RS = _STUDIO / "src-tauri" / "src" / "diagnostics" / "mod.rs"+_PROCESS_RS = _STUDIO / "src-tauri" / "src" / "process.rs"++# Families that write one file per operation and prune nothing, so the directory grows for+# the life of the install. Recorded rather than asserted away, and self-expiring: the test+# below fails once a family here gains retention, which forces the entry out.+#+# llama-server / diffusion-server: one file per model load ATTEMPT. 319 files going back+# two months were found on one machine. Retention arrives with #8763.+# Empty since #8763 gave the two sidecar families keep-newest-N retention. The staleness+# check below fails on an entry that no longer describes reality, so this list cannot+# outlive the problem it records.+KNOWN_UNBOUNDED_FAMILIES: frozenset[str] = frozenset()++# Families the desktop shell owns. Bounded in Rust (rotation), not by a Python pruner.+_DESKTOP_FAMILIES = frozenset(+ {+ "desktop-backend",+ "desktop-install",+ "desktop-update",+ "desktop-repair",+ "desktop-shell",+ }+)+++def _python_retention_sources() -> str:+ """Every Python file that could plausibly prune a log directory."""+ backend = Path(_BACKEND_DIR)+ parts = []+ for relative in ("run.py", "utils/log_retention.py", "core/inference/llama_cpp.py"):+ path = backend / relative+ if path.is_file():+ parts.append(path.read_text(encoding = "utf-8", errors = "replace"))+ return "\n".join(parts)+++class TestFamiliesAreBounded:+ def test_every_python_written_family_prunes(self):+ """A family that never prunes grows without limit.++ Detected from the glob in FAMILIES appearing next to a retention call site, which+ is deliberately loose: the point is to notice a family that nobody thought about,+ not to pin how the pruning is spelled.+ """+ source = _python_retention_sources()+ unbounded = []+ for family, (_subdir, glob) in debug_log_sources.FAMILIES.items():+ if family in _DESKTOP_FAMILIES:+ continue+ if glob not in source:+ unbounded.append(f"{family} ({glob})")++ new = sorted(+ set(unbounded)+ - {f"{f} ({debug_log_sources.FAMILIES[f][1]})" for f in KNOWN_UNBOUNDED_FAMILIES}+ )+ assert not new, (+ "these log families are written but never pruned, so they grow for the life "+ "of the install:\n "+ + "\n ".join(new)+ + "\n\nPrune them where they are opened, keeping the newest N and protecting "+ "the handle you just opened."+ )++ def test_the_unbounded_list_does_not_outlive_the_problem(self):+ source = _python_retention_sources()+ stale = sorted(+ family+ for family in KNOWN_UNBOUNDED_FAMILIES+ if family in debug_log_sources.FAMILIES+ and debug_log_sources.FAMILIES[family][1] in source+ )+ assert not stale, (+ "these families now prune but are still listed in "+ "KNOWN_UNBOUNDED_FAMILIES:\n "+ + "\n ".join(stale)+ + "\n\nDelete the entries so the list keeps meaning something."+ )++ def test_a_new_family_cannot_be_added_unnoticed(self):+ """FAMILIES is the inventory; adding to it is a decision about disk growth."""+ reviewed = {+ "server",+ "llama-server",+ "diffusion-server",+ "desktop-backend",+ "desktop-install",+ "desktop-update",+ "desktop-repair",+ "desktop-shell",+ }+ actual = set(debug_log_sources.FAMILIES)+ added = sorted(actual - reviewed)+ assert not added, (+ "new log families:\n "+ + "\n ".join(added)+ + "\n\nGive each one retention, then add it to the reviewed list here. A "+ "family with no pruning is an install that grows until the disk is full."+ )+++class TestLineCapsAgree:+ def test_the_desktop_line_cap_matches_the_phase_log(self):+ """One line, two sinks, one length. A cap on one only is a silent asymmetry."""+ if not _DIAGNOSTICS_RS.is_file():+ pytest.skip("desktop sources not present")+ phase = re.search(+ r"MAX_PHASE_LINE_BYTES: usize = ([0-9 *]+);",+ _DIAGNOSTICS_RS.read_text(encoding = "utf-8"),+ )+ assert phase is not None, (+ "MAX_PHASE_LINE_BYTES is no longer a plain literal in diagnostics/mod.rs; "+ "this test reads it to compare the two caps"+ )+ phase_bytes = eval(phase.group(1).strip()) # noqa: S307 - digits and '*' only++ process = _PROCESS_RS.read_text(encoding = "utf-8") if _PROCESS_RS.is_file() else ""+ backend_cap = re.search(r"MAX_BACKEND_LOG_LINE_BYTES: usize = ([0-9 *]+);", process)+ if backend_cap is None:+ pytest.skip(+ "the desktop shell does not cap mirrored backend lines on this revision; "+ "this check activates when that lands"+ )+ backend_bytes = eval(backend_cap.group(1).strip()) # noqa: S307++ assert backend_bytes == phase_bytes, (+ f"tauri.log caps a backend line at {backend_bytes} bytes but the phase log "+ f"caps the same line at {phase_bytes}. The same line would be truncated on one "+ "sink and not the other, which is what makes two logs of one event disagree."+ )++ def test_the_desktop_log_still_rotates_by_size(self):+ """Keeping N files is not a bound if any one of them can be any size."""+ if not _MAIN_RS.is_file():+ pytest.skip("desktop sources not present")+ source = _MAIN_RS.read_text(encoding = "utf-8")+ assert "RotatingLogFile" in source, (+ "tauri.log no longer uses RotatingLogFile, so nothing bounds its size while "+ "the app runs"+ )+ assert re.search(r"max_log_bytes\s*=\s*[0-9 *]+;", source), (+ "the tauri.log rotation threshold is gone; a session left open for days grows "+ "the file until the next restart"+ )diff --git a/studio/backend/tests/test_log_budget.py b/studio/backend/tests/test_log_budget.pynew file mode 100644index 00000000000..296ffdfc27b--- /dev/null+++ b/studio/backend/tests/test_log_budget.py@@ -0,0 +1,214 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Log volume must not regress, and every polled path must be classified.++Studio's log-reduction work is several PRs deep and every round of it started with someone+noticing a log was huge. Nothing stopped the next chatty endpoint. These are the two guards+that do: an envelope on how much an idle app writes, and a closure check that makes it+impossible to add a poll without saying which suppression rule owns it.++The counts here are derived from a formula over the poll period and the de-duplication+window, not recorded from a run, so changing a poll interval moves the expectation with it+and only a genuine rule violation fails.++See ``test_log_signal_floor.py`` for the other half: these tests cap how much is written,+that one guarantees the important things still are.+"""++from __future__ import annotations++import sys+from collections import Counter+from pathlib import Path++import pytest++# Same idiom as test_server_disk_logging.py: make the import work regardless of which+# directory pytest was invoked from, rather than depending on the rootdir it picked.+_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++from loggers import handlers as hmod # noqa: E402+from log_budget import policy, replay, session # noqa: E402+++def _classes_present(paths) -> dict[str, list[str]]:+ grouped: dict[str, list[str]] = {}+ for path in paths:+ grouped.setdefault(policy.classify(hmod, path), []).append(path)+ return grouped+++class TestClassificationClosure:+ """Guard B. The registry and the middleware's own sets must describe the same world."""++ def test_every_classified_path_is_in_a_scenario(self):+ """A path cannot be quieted without saying how often it is polled.++ Otherwise a path joins ``_QUIET_POLL_PATHS`` for a reason nobody records, and the+ budget never sees it because no scenario asks for it.+ """+ classified = set()+ for attr in (+ "_QUIET_POLL_PATHS",+ "_LIVENESS_POLL_PATHS",+ "_WATCHDOG_POLL_PATHS",+ "_QUIET_SUCCESS_PATHS",+ "_CHAT_LIST_PATHS",+ "_SELF_READ_PATHS",+ "_EXCLUDED_PATHS",+ ):+ classified |= set(getattr(hmod, attr, ()) or ())++ missing = sorted(classified - set(session.ALL_POLLS))+ assert not missing, (+ "these paths are classified in loggers/handlers.py but no scenario in "+ "tests/log_budget/session.py polls them, so their log volume is unmeasured:\n "+ + "\n ".join(missing)+ + "\n\nAdd each to IDLE_POLLS (polled when nothing is happening) or BUSY_POLLS "+ "(polled only during an operation) with its interval."+ )++ def test_every_polled_path_has_exactly_one_class(self):+ """And a poll cannot be added without choosing a rule for it.++ ``classify`` returns ``normal`` for anything unlisted, which is a real class with a+ 300 ms window, so the check is that the choice was deliberate: a path polled faster+ than a few seconds and left in ``normal`` logs on essentially every request.+ """+ 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+ }++ new = sorted(offenders - session.KNOWN_UNCLASSIFIED_POLLS)+ assert not new, (+ "these paths are polled further apart than the `normal` window of "+ f"{hmod._ACCESS_LOG_DEDUP_MS} ms, so every single poll writes a line:\n "+ + "\n ".join(f"{path} every {session.ALL_POLLS[path][0]:g}s" for path in new)+ + f"\n\nPick a heartbeat class in loggers/handlers.py: "+ f"{', '.join(policy.ALL_CLASSES)}."+ )++ # The other direction, so the ledger cannot outlive the problem it records.+ fixed = sorted(session.KNOWN_UNCLASSIFIED_POLLS - offenders)+ assert not fixed, (+ "these paths are listed in KNOWN_UNCLASSIFIED_POLLS but now have a heartbeat "+ "class, so the entry is stale:\n "+ + "\n ".join(fixed)+ + "\n\nDelete them from tests/log_budget/session.py and tighten the envelopes."+ )++ def test_scenarios_do_not_overlap(self):+ both = sorted(set(session.IDLE_POLLS) & set(session.BUSY_POLLS))+ assert not both, (+ "a path must belong to exactly one scenario or its lines are counted twice:\n "+ + "\n ".join(both)+ )+++class TestVolumeEnvelope:+ """Guard A. How much the app writes, and whether it honours its own windows."""++ @pytest.mark.parametrize(+ "label, polls, duration, envelope",+ [+ (+ "steady idle",+ session.IDLE_POLLS,+ session.STEADY_IDLE_SECONDS,+ session.STEADY_IDLE_LINE_ENVELOPE,+ ),+ (+ "operation in flight",+ session.BUSY_POLLS,+ session.BUSY_SECONDS,+ session.BUSY_LINE_ENVELOPE,+ ),+ ],+ )+ def test_scenario_stays_inside_its_envelope(+ self, label, polls, duration, envelope, monkeypatch+ ):+ result = replay.replay(hmod, monkeypatch, polls, duration)+ counts = Counter(result.capture.paths())++ if result.emitted > envelope:+ worst = "\n ".join(+ f"{n:5d} {path} [{policy.classify(hmod, path)}]"+ for path, n in counts.most_common(8)+ )+ pytest.fail(+ f"{label}: {result.emitted} log lines over {duration / 60:.0f} virtual "+ f"minutes, envelope is {envelope}.\n"+ f"Biggest contributors:\n {worst}\n\n"+ "If you added an endpoint, give it a heartbeat class in "+ "loggers/handlers.py rather than raising the envelope. Raising it is a "+ "decision about how much Studio is allowed to write when nobody is using "+ "it."+ )++ @pytest.mark.parametrize(+ "label, polls, duration",+ [+ ("steady idle", session.IDLE_POLLS, session.STEADY_IDLE_SECONDS),+ ("operation in flight", session.BUSY_POLLS, session.BUSY_SECONDS),+ ],+ )+ def test_each_path_matches_its_class_formula(self, label, polls, duration, monkeypatch):+ """The window is honoured exactly, not merely under a ceiling.++ A ceiling alone would pass if suppression stopped working and something else got+ quieter. Checking the derived count catches the rule itself breaking.+ """+ result = replay.replay(hmod, monkeypatch, polls, duration)+ counts = Counter(result.capture.paths())++ mismatches = []+ for path, (period, _provenance) in polls.items():+ # Shared buckets are asserted below; a member that is not the bucket owner+ # legitimately emits zero.+ if policy.bucket_of(hmod, path) != path:+ continue+ cls = policy.classify(hmod, path)+ expected = policy.expected_emissions(policy.window_ms(hmod, cls), period, duration)+ actual = counts.get(path, 0)+ if actual != expected:+ mismatches.append(+ f"{path} [{cls}] polled every {period}s: emitted {actual}, "+ f"the {policy.window_ms(hmod, cls)}ms window implies {expected}"+ )++ assert not mismatches, (+ f"{label}: these paths did not log the number of times their suppression class "+ "implies:\n " + "\n ".join(mismatches)+ )++ def test_the_liveness_burst_collapses_to_one_bucket(self, monkeypatch):+ """The five liveness paths answer one question and must cost one line, not five.++ Asserted on the bucket total rather than on which path won it: the SPA fires them+ together and whichever arrives first legitimately takes the line.+ """+ liveness = {+ path: value+ for path, value in session.IDLE_POLLS.items()+ if policy.classify(hmod, path) == policy.LIVENESS+ }+ if not liveness:+ pytest.skip("no liveness paths configured in this revision")++ result = replay.replay(hmod, monkeypatch, liveness, session.STEADY_IDLE_SECONDS)+ fastest = min(period for period, _ in liveness.values())+ expected = policy.expected_emissions(+ policy.window_ms(hmod, policy.LIVENESS), fastest, session.STEADY_IDLE_SECONDS+ )+ assert result.emitted == expected, (+ f"{len(liveness)} liveness paths polled together produced {result.emitted} "+ f"lines; sharing one bucket implies {expected}. If a path left "+ "_LIVENESS_POLL_PATHS it now heartbeats on its own and costs a line per window."+ )diff --git a/studio/backend/tests/test_log_rule_parity.py b/studio/backend/tests/test_log_rule_parity.pynew file mode 100644index 00000000000..6e02838f1c8--- /dev/null+++ b/studio/backend/tests/test_log_rule_parity.py@@ -0,0 +1,121 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""One definition of "a successful access record", in two languages.++The backend decides whether to emit an access line; the desktop shell decides whether to+mirror it into ``tauri.log``. Two implementations of the same idea, in two languages and+two processes, with nothing holding them together. The pair already drifted once: the+Python tee and the Rust ``collapse_progress_frames`` disagreed about CRLF, so a Windows+traceback survived on one sink and became blank lines on the other.++``tests/fixtures/access_log_records.json`` is the shared contract. This module checks the+Python side and, once the desktop-side filter exists, checks that the Rust side was written+against the same rule. The matching ``#[test]`` in ``process.rs`` consumes the same file, so+changing the rule on either side turns the other red.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++import pytest++_FIXTURE = Path(__file__).resolve().parent / "fixtures" / "access_log_records.json"+_PROCESS_RS = Path(__file__).resolve().parents[2] / "src-tauri" / "src" / "process.rs"+++def _cases():+ return json.loads(_FIXTURE.read_text(encoding = "utf-8"))["cases"]+++def is_successful_access_record(line: str) -> bool:+ """The contract, in Python. ``keep`` in the fixture is the negation of this."""+ trimmed = line.lstrip()+ if not trimmed.startswith("{"):+ return False+ try:+ record = json.loads(trimmed)+ except ValueError:+ return False+ if not isinstance(record, dict):+ return False+ if record.get("event") != "request_completed":+ return False+ status = record.get("status_code")+ if not isinstance(status, int) or isinstance(status, bool):+ return False+ return 200 <= status <= 299++[email protected]("case", _cases(), ids = lambda c: c["name"])+def test_python_side_matches_the_shared_fixture(case):+ dropped = is_successful_access_record(case["line"])+ assert dropped != case["keep"], (+ f"{case['name']}: the fixture says keep={case['keep']} ({case['why']}) but the "+ f"Python rule says this line is {'a' if dropped else 'not a'} successful access "+ "record. Update both sides together, or the two sinks stop agreeing."+ )+++def test_the_fixture_still_covers_the_edges():+ """Guard the guard: a fixture quietly emptied of hard cases proves nothing."""+ names = {case["name"] for case in _cases()}+ required = {+ "199 is not success",+ "300 is not success",+ "request_completed with no status_code",+ "malformed JSON",+ "a different structured event",+ }+ missing = sorted(required - names)+ assert not missing, (+ "these boundary cases were removed from access_log_records.json:\n "+ + "\n ".join(missing)+ + "\nThey are the cases where the two implementations are most likely to diverge."+ )+++class TestRustSide:+ """Checked from Python so a divergence fails even in a Python-only CI job."""++ def _source(self) -> str:+ if not _PROCESS_RS.is_file():+ pytest.skip(f"{_PROCESS_RS} not present")+ return _PROCESS_RS.read_text(encoding = "utf-8")++ def test_the_desktop_filter_uses_the_same_success_range(self):+ source = self._source()+ if "fn is_backend_access_log_line" not in source:+ pytest.skip(+ "the desktop shell does not filter successful access records on this "+ "revision; this check activates when that lands"+ )++ match = re.search(r"Some\((\d+)\.\.=(\d+)\)", source)+ assert match is not None, (+ "is_backend_access_log_line no longer matches a Some(lo..=hi) status range, "+ "which is how this test reads the rule. Update the test alongside it."+ )+ low, high = int(match.group(1)), int(match.group(2))+ assert (low, high) == (200, 299), (+ f"the desktop shell treats {low}..={high} as success while the backend and "+ "tests/fixtures/access_log_records.json use 200..=299. A line dropped on one "+ "sink and kept on the other is exactly the drift this fixture exists to catch."+ )++ assert (+ '"request_completed"' in source+ ), "is_backend_access_log_line no longer keys on the request_completed event"++ def test_the_rust_test_consumes_the_shared_fixture(self):+ source = self._source()+ if "fn is_backend_access_log_line" not in source:+ pytest.skip("desktop-side filter not present on this revision")+ assert "access_log_records.json" in source, (+ "process.rs implements the success rule but no Rust test reads "+ "tests/fixtures/access_log_records.json, so the two languages are only "+ "checked from the Python side. Add the shared-fixture #[test]."+ )diff --git a/studio/backend/tests/test_log_signal_floor.py b/studio/backend/tests/test_log_signal_floor.pynew file mode 100644index 00000000000..2ea38e55834--- /dev/null+++ b/studio/backend/tests/test_log_signal_floor.py@@ -0,0 +1,337 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Nothing that matters may ever be suppressed, and the budget may not be met by deleting.++``test_log_budget.py`` caps how much gets written. On its own that is a dangerous test: an+upper bound 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 a developer who deleted+an error log to get under the number. Every one of those is a worse outcome than the+regression the cap exists to catch.++So this file asserts the floor. Failures and mutations log every time at any interval, and+the replay is proved to have actually exercised the real middleware before any of it counts.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++from loggers import handlers as hmod # noqa: E402+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)+MUTATING_METHODS = ("POST", "PUT", "PATCH", "DELETE")+++def _drive(+ monkeypatch,+ requests,+ gap_s = 0.0,+):+ """Send requests through one middleware instance, advancing the clock by `gap_s`."""+ from loggers.handlers import LoggingMiddleware++ clock = replay.install(hmod, monkeypatch)+ capture = replay.LogCapture()+ monkeypatch.setattr(hmod, "logger", capture)+ middleware = LoggingMiddleware(replay._app_returning(200))++ for request in requests:+ middleware.app = replay._app_returning(request.status, request.duration_ms, clock)+ scope = {+ "type": "http",+ "path": request.path,+ "method": request.method,+ "query_string": request.query,+ }+ import asyncio++ asyncio.run(middleware(scope, replay._noop_receive, replay._noop_send))+ clock.advance(gap_s)+ return capture+++class TestFailuresAreNeverSuppressed:+ """A failing poll must log every time, however fast it repeats."""++ @pytest.mark.parametrize("status", FAILURE_STATUSES)+ def test_repeated_failures_all_log_on_every_classified_path(self, status, monkeypatch):+ # Zero gap: the worst case for any window-based suppressor.+ #+ # The `excluded` class is left out because it is the one suppressor that is NOT+ # gated on a 2xx: `__call__` drops the path before the status is considered, so a+ # 500 on /api/train/status is invisible here. That is existing behaviour, not+ # something this guard can assert away; it is pinned instead by+ # test_the_excluded_set_is_exactly_what_was_reviewed below.+ paths = sorted(+ p+ for p in session.ALL_POLLS+ if policy.classify(hmod, p) != policy.EXCLUDED+ # Chat-list 401s have one narrow, deliberate exemption during the bootstrap+ # token race. Its exact boundaries are pinned by+ # test_the_chat_list_401_exemption_is_only_pre_auth rather than waved through.+ and not (status == 401 and p in hmod._CHAT_LIST_PATHS)+ )+ requests = [+ replay.Request(method = "GET", path = path, status = status)+ for path in paths+ for _ in range(3)+ ]+ capture = _drive(monkeypatch, requests, gap_s = 0.0)++ logged = [kw.get("path") for _lvl, _ev, kw in capture.events]+ missing = sorted({p for p in paths if logged.count(p) != 3})+ assert not missing, (+ f"a {status} response was de-duplicated on these paths, so a user hitting a "+ "repeated failure would see one line instead of every occurrence:\n "+ + "\n ".join(missing)+ + "\n\nSuppression must be gated on a 2xx status. See _is_redundant_repeat and "+ "_is_quiet_success in loggers/handlers.py."+ )++ @pytest.mark.parametrize("method", MUTATING_METHODS)+ def test_repeated_mutations_all_log(self, method, monkeypatch):+ requests = [+ replay.Request(method = method, path = "/api/chat/threads", status = 200) for _ in range(3)+ ]+ capture = _drive(monkeypatch, requests, gap_s = 0.0)+ assert len(capture.events) == 3, (+ f"three identical {method} requests produced {len(capture.events)} lines. "+ "Mutations change state and must never be collapsed, however fast they repeat."+ )++ def test_a_failure_inside_a_quiet_window_still_logs(self, monkeypatch):+ """The case that matters most: a poll that was quiet and starts failing."""+ quiet = [+ p+ for p in session.ALL_POLLS+ if policy.classify(hmod, p) in (policy.QUIET, policy.LIVENESS)+ ]+ assert quiet, "no quiet-poll paths configured; this guard would be vacuous"+ path = sorted(quiet)[0]++ capture = _drive(+ monkeypatch,+ [+ replay.Request("GET", path, 200),+ replay.Request("GET", path, 200), # collapsed, correctly+ replay.Request("GET", path, 503), # must not be+ replay.Request("GET", path, 503),+ ],+ gap_s = 0.0,+ )++ failures = [kw for _l, _e, kw in capture.events if kw.get("status_code") == 503]+ assert len(failures) == 2, (+ f"{path} went from healthy to failing inside its heartbeat window and only "+ f"{len(failures)} of 2 failures were logged. A watchdog going red is exactly "+ "what these logs are read for."+ )++ def test_the_chat_list_401_exemption_is_only_pre_auth(self, monkeypatch):+ """The one status-specific exemption, held to its stated scope.++ A chat list poll racing the first token refresh answers 401 for reasons that are+ not a problem, so it is suppressed. Once a refresh has succeeded a 401 means+ something real and must log. An exemption that quietly widened past the bootstrap+ window would hide genuine auth failures for the rest of the session.+ """+ from loggers.handlers import LoggingMiddleware+ import asyncio++ path = sorted(hmod._CHAT_LIST_PATHS)[0]+ replay.install(hmod, monkeypatch)+ capture = replay.LogCapture()+ monkeypatch.setattr(hmod, "logger", capture)+ middleware = LoggingMiddleware(replay._app_returning(401))++ def send(status):+ middleware.app = replay._app_returning(status)+ asyncio.run(+ middleware(+ {"type": "http", "path": path, "method": "GET", "query_string": b""},+ replay._noop_receive,+ replay._noop_send,+ )+ )++ send(401)+ assert not capture.events, (+ "the bootstrap 401 on a chat list poll should be suppressed before the first "+ "successful refresh"+ )++ # A 500 is not covered by the exemption even during bootstrap.+ send(500)+ assert (+ len(capture.events) == 1+ ), "only 401 is exempt during bootstrap; a 500 on the same path must log"++ # After a refresh succeeds, a 401 is real.+ middleware._auth_refreshed = True+ send(401)+ assert len(capture.events) == 2, (+ "a 401 after the first successful token refresh is a real auth failure and "+ "must be logged; the bootstrap exemption has widened past its window"+ )++ def test_the_excluded_set_is_exactly_what_was_reviewed(self):+ """The one class where a failure genuinely does disappear.++ Every other suppressor checks the status first, so a 4xx or 5xx always logs. The+ ``excluded`` check in ``LoggingMiddleware.__call__`` runs before the status is+ known, so these paths log nothing at all, including a 500. That may be the right+ trade for a metrics endpoint polled twice a second, but it should never grow by+ accident: adding a path here means accepting that its failures are invisible in the+ access log.+ """+ reviewed = {+ "/api/system",+ "/api/train/hardware",+ "/api/train/metrics",+ "/api/train/status",+ }+ actual = set(hmod._EXCLUDED_PATHS)+ assert actual == reviewed, (+ "_EXCLUDED_PATHS changed. Unlike the heartbeat classes this one drops errors "+ "too, so a path added here will never report a failure in the access log.\n"+ f" added: {sorted(actual - reviewed)}\n"+ f" removed: {sorted(reviewed - actual)}\n"+ "If the addition is intended, update this list and say why the path's failures "+ "do not need to be visible."+ )+++class TestTheGuardIsNotVacuous:+ """Prove the replay exercised the real thing before trusting any count from it."""++ def test_the_replay_actually_reaches_the_middleware(self, monkeypatch):+ result = replay.replay(hmod, monkeypatch, session.IDLE_POLLS, 60.0, session.BOOT_REQUESTS)+ assert result.sent, "the scenario issued no requests at all"+ assert result.emitted > 0, (+ "the replay produced zero log lines. Every budget assertion would pass "+ "trivially. Either the middleware is not mounted or the capture is not the "+ "logger it calls."+ )++ def test_the_capture_is_the_logger_the_middleware_calls(self, monkeypatch):+ """A no-op logger would satisfy every ceiling in the budget file."""+ capture = _drive(monkeypatch, [replay.Request("GET", "/api/nope", 404)])+ assert hmod.logger is capture, (+ "the middleware is not logging through the captured object, so the budget "+ "tests are measuring nothing"+ )+ assert capture.events, "a 404 produced no record through the real middleware"++ def test_boot_emits_one_mutation_and_one_failure_sentinel(self, monkeypatch):+ """Lower bounds on the known-good scenario, so silent deletion fails here."""+ result = replay.replay(hmod, monkeypatch, {}, 0.0, session.BOOT_REQUESTS)+ records = [kw for _l, _e, kw in result.capture.events]++ mutations = [r for r in records if r.get("method") in MUTATING_METHODS]+ failures = [+ r+ for r in records+ if isinstance(r.get("status_code"), int) and not 200 <= r["status_code"] < 300+ ]+ successes = [+ r+ for r in records+ if isinstance(r.get("status_code"), int) and 200 <= r["status_code"] < 300+ ]++ assert len(mutations) == 1, (+ f"boot should log exactly one mutation, saw {len(mutations)}. "+ "If the login POST stopped being logged, mutation logging has regressed."+ )+ assert len(failures) == 1, (+ f"boot should log exactly one failure, saw {len(failures)}. "+ "The pre-auth 401 is the sentinel that proves failures survive."+ )+ assert successes, (+ "boot logged no successful request at all. Suppression has gone too far, or "+ "the scenario stopped issuing requests."+ )++ def test_every_scenario_path_is_actually_requested(self, monkeypatch):+ """A path that quietly stops being polled would lower every count for free."""+ result = replay.replay(hmod, monkeypatch, session.ALL_POLLS, 60.0)+ requested = {r.path for r in result.sent}+ missing = sorted(set(session.ALL_POLLS) - requested)+ assert not missing, (+ "the replay never issued these registered polls, so their budget is "+ "meaningless:\n " + "\n ".join(missing)+ )+++class TestSlowSuccessIsNotYetSignal:+ """A 200 that took a minute is treated exactly like a 200 that took a millisecond.++ Both suppressors key on the STATUS CODE. Nothing anywhere reads how long the request+ took, so a degrading endpoint stays invisible for as long as it keeps returning 2xx.++ These tests assert the CURRENT behaviour rather than the desired one, on purpose. The+ gap is real and worth closing, but a guard that silently tolerates either answer would+ let the exemption be added and then removed again without anyone noticing. Closing it+ should flip these deliberately, with the new volume budgeted the same way as every+ other line here.+ """++ SLOW_MS = 30_000.0++ def _slow_lines(+ self,+ monkeypatch,+ path,+ count = 6,+ ):+ capture = _drive(+ monkeypatch,+ [replay.Request("GET", path, 200, duration_ms = self.SLOW_MS) for _ in range(count)],+ gap_s = 0.0,+ )+ return capture.records_for(path)++ def test_a_slow_success_on_a_silent_path_writes_nothing(self, monkeypatch):+ silent = sorted(+ p for p in session.ALL_POLLS if policy.classify(hmod, p) == policy.QUIET_SUCCESS+ )+ assert silent, "no quiet-success paths configured; this guard would be vacuous"+ path = silent[0]++ records = self._slow_lines(monkeypatch, path)+ assert records == [], (+ f"{path} now logs a slow success ({len(records)} line(s)). If that is the "+ "intended change, budget it: a sustained degradation on a 5s poll emits one "+ "line per request unless the slow line gets a heartbeat of its own."+ )++ def test_the_harness_can_tell_a_slow_request_from_a_fast_one(self, monkeypatch):+ """Guards the guard: without this, the two tests around it are vacuous.++ ``duration_ms`` has to actually reach the middleware's clock. If it silently did+ nothing, every 'slow' case above would really be a fast one and would pass for the+ wrong reason.+ """+ path = "/api/models/list"+ capture = _drive(+ monkeypatch,+ [replay.Request("GET", path, 200, duration_ms = self.SLOW_MS)],+ gap_s = 0.0,+ )+ records = capture.records_for(path)+ assert records, f"{path} is in the normal class and should log on the first hit"+ assert records[0]["process_time_ms"] >= self.SLOW_MS, (+ "duration_ms did not reach the middleware: it recorded "+ f"{records[0]['process_time_ms']}ms for a {self.SLOW_MS}ms request, so every "+ "slow-path assertion here is really testing a fast request."+ )diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rsindex 96ccf8c93c8..79a5377caaa 100644--- a/studio/src-tauri/src/process.rs+++ b/studio/src-tauri/src/process.rs@@ -4438,6 +4438,50 @@ mod backend_log_line_tests {}}+/// The same corpus the backend checks itself against.+///+/// Two implementations of "a successful access record", in two languages and two+/// processes: the backend decides whether to emit the line at all, and the shell decides+/// whether to mirror it into `tauri.log`. They can drift, and the CRLF handling in the+/// progress-frame collapsers already did drift once. Reading one file from both sides+/// turns a change to the rule on either side red on the other.+#[cfg(test)]+mod shared_access_log_fixture_tests {+ use super::*;++ #[test]+ fn every_shared_case_agrees_with_the_desktop_filter() {+ 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}"));+ let fixture: serde_json::Value =+ serde_json::from_str(&raw).expect("the shared fixture is not valid JSON");+ let cases = fixture["cases"]+ .as_array()+ .expect("the shared fixture has no `cases` array");+ assert!(!cases.is_empty(), "the shared fixture is empty, so this test proves nothing");++ for case in cases {+ let name = case["name"].as_str().unwrap_or("<unnamed>");+ let line = case["line"].as_str().unwrap_or_else(|| {+ panic!("case {name:?} has no `line`");+ });+ let keep = case["keep"]+ .as_bool()+ .unwrap_or_else(|| panic!("case {name:?} has no boolean `keep`"));+ // keep=false means the line IS a successful access record, which is exactly+ // when the filter returns true and the line drops to debug.+ assert_eq!(+ is_backend_access_log_line(line),+ !keep,+ "case {name:?}: {}",+ case["why"].as_str().unwrap_or("no rationale recorded")+ );+ }+ }+}+// A login-started desktop on Windows inherits C:\Windows\system32 (issue #8510),// and so did every CLI child, where the Python CLI refuses to run. These pin the// replacement directory and that each command carries it.diff --git a/tests/studio/playwright_declared_polls.py b/tests/studio/playwright_declared_polls.pynew file mode 100644index 00000000000..966ffc5c044--- /dev/null+++ b/tests/studio/playwright_declared_polls.py@@ -0,0 +1,270 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Every path the idle app polls must be declared in the log budget.++The budget suite in ``studio/backend/tests/log_budget`` checks two backend files against+each other: the suppression sets in ``loggers/handlers.py`` and the poll cadences in+``log_budget/session.py``. That catches quieting a path without declaring it, and+declaring a path without classifying it.++It cannot catch the case this exists for. A pull request that adds a polling call site in+the frontend touches neither file, so nothing fails, the new endpoint quietly lands in the+``normal`` class on a 300 ms window, and the access log grows by 12 lines a minute that+nobody chose. That is how the last several log-volume PRs became necessary.++Static analysis does not close it either: polling here is 53 ``setInterval`` call sites,+most of which are UI timers rather than fetches, plus 257 ``setTimeout`` of which an+unknown number are recursive poll loops, and the fetch is usually several helper layers+below the timer. So observe the browser instead. Whatever a path is polled BY, it shows up+here.++What this reaches, and what it does not. It sees any poll that runs unconditionally on a+screen the walk visits, which is where a newly added ``setInterval`` normally lands. It+does NOT see polls gated behind state a bare runner cannot reach: with no GPU and no model+loaded, the loaded-models indicator and the training views never start their timers, and+Train is not even clickable. Measured on such a runner the observable set is two paths. So+treat this as a net with a known mesh size rather than a proof that no new poll exists.++Run: BASE_URL, STUDIO_OLD_PW and STUDIO_NEW_PW as the other suites take them.+"""++from __future__ import annotations++import json+import os+import sys+import urllib.error+import urllib.request+from collections import Counter+from pathlib import Path+from urllib.parse import urlsplit++from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ install_wall_clock_watchdog,+ wait_for_health,+)++_REPO = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(_REPO / "studio" / "backend" / "tests"))+from log_budget.session import ALL_POLLS # noqa: E402++BASE = os.environ["BASE_URL"]+OLD = os.environ["STUDIO_OLD_PW"]+NEW = os.environ["STUDIO_NEW_PW"]+ART = Path(os.environ.get("PW_ART_DIR", "logs/playwright-declared-polls"))+ART.mkdir(parents = True, exist_ok = True)++# How long to watch, once the app has stopped booting.+SETTLE_S = float(os.environ.get("PW_POLL_SETTLE_S", "20"))+WATCH_S = float(os.environ.get("PW_POLL_WATCH_S", "75"))+WALL_TIMEOUT_S = SETTLE_S + WATCH_S + 180++# A boot read fires once. A retry fires twice. Three identical requests while the user is+# doing nothing at all is a timer, and the threshold is deliberately this blunt: anything+# cleverer (spacing regularity, variance) turns a gate into a coin toss on a shared runner.+POLL_THRESHOLD = 3++# Sidebar sections to walk, so section-scoped timers get a chance to run.+SECTIONS = ("Model hub", "Projects", "Images", "Train", "New chat")++# The floor that stops this suite passing on a run that observed nothing at all. Measured,+# not guessed: a walk over the sections above on a runner with no GPU and no model sees+# exactly two paths repeat inside a dwell, /api/inference/monitor and /api/export/status.+# Anything less means the listener never attached or the page never rendered.+MIN_POLLED_PATHS = int(os.environ.get("PW_POLL_MIN_PATHS", "2"))+++def info(message: str) -> None:+ print(message, flush = True)+++def api(+ path: str,+ payload: dict,+ token: str | None = None,+) -> dict:+ request = urllib.request.Request(+ f"{BASE}{path}",+ data = json.dumps(payload).encode(),+ headers = {+ "Content-Type": "application/json",+ **({"Authorization": f"Bearer {token}"} if token else {}),+ },+ )+ with urllib.request.urlopen(request, timeout = 30) as response:+ return json.loads(response.read().decode() or "{}")+++def normalize(url: str) -> str:+ """Path only. The query string is part of the dedup identity in the middleware, but a+ poll declares a PATH, and a cursor or cache-buster would otherwise make every hit look+ unique and hide the poll entirely."""+ return urlsplit(url).path+++def main() -> int:+ declared = set(ALL_POLLS)++ if not wait_for_health(BASE, info = info):+ info("FAIL backend never became healthy")+ return 1++ # Bootstrap as the sibling suites do: the first login forces a change. Tolerate the+ # rotation having already happened, because a second suite against the same instance+ # would otherwise die on a 401 traceback instead of just logging in.+ try:+ token = api("/api/auth/login", {"username": "unsloth", "password": OLD})["access_token"]+ except urllib.error.HTTPError as exc:+ if exc.code != 401:+ raise+ token = None+ if token is not None:+ try:+ api("/api/auth/change-password", {"current_password": OLD, "new_password": NEW}, token)+ except urllib.error.HTTPError:+ pass+ session = api("/api/auth/login", {"username": "unsloth", "password": NEW})++ seed_js = (+ "(() => {"+ f" localStorage.setItem('unsloth_auth_token', {json.dumps(session['access_token'])});"+ f" localStorage.setItem('unsloth_refresh_token', "+ f"{json.dumps(session.get('refresh_token', ''))});"+ "})();"+ )++ seen: Counter[str] = Counter()+ # Counts are attributed to the current dwell, never summed across the walk. Visiting+ # five sections fetches a per-view endpoint five times, which is indistinguishable from+ # a 30s timer if you only look at the total. A timer repeats WITHIN one dwell; a+ # per-view fetch fires once and stops. The per-dwell maximum is the honest signal.+ dwell_counts: Counter[str] = Counter()+ per_dwell_max: Counter[str] = Counter()+ counting = False++ def close_dwell() -> None:+ for path, n in dwell_counts.items():+ if n > per_dwell_max[path]:+ per_dwell_max[path] = n+ dwell_counts.clear()++ with sync_playwright() as p:+ install_wall_clock_watchdog(WALL_TIMEOUT_S, label = "declared-polls", info = info)+ browser = p.chromium.launch(headless = True, args = chromium_launch_args())+ context = browser.new_context(+ viewport = {"width": 1440, "height": 900}, reduced_motion = "reduce"+ )+ context.add_init_script(seed_js)+ page = context.new_page()++ def on_request(request) -> None:+ if not counting:+ return+ path = normalize(request.url)+ if path.startswith("/api/"):+ seen[path] += 1+ dwell_counts[path] += 1++ page.on("request", on_request)+ page.goto(BASE, wait_until = "domcontentloaded", timeout = 60_000)++ # Boot traffic is one-shot by nature and would otherwise be indistinguishable from+ # a slow poll over a short window. Let it drain before counting anything.+ page.wait_for_timeout(int(SETTLE_S * 1000))+ counting = True++ # Sitting on the default screen sees almost nothing: measured, the chat view polls+ # 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)+ for label in SECTIONS:+ try:+ page.get_by_text(label, exact = True).first.click(timeout = 8_000)+ except Exception:+ info(f"note: could not reach {label!r}")+ continue+ page.wait_for_timeout(dwell)+ close_dwell()+ page.wait_for_timeout(dwell) # a final idle dwell wherever we ended up+ close_dwell()+ counting = False++ current = normalize(page.url)+ context.close()+ browser.close()++ if current.startswith(("/login", "/change-password")):+ # Every counted request would be the login screen's, which polls almost nothing.+ # Without this the suite passes by observing an app it never entered.+ info(f"FAIL still on {current} after seeding a token; the run proved nothing")+ return 1++ polled = {path: n for path, n in per_dwell_max.items() if n >= POLL_THRESHOLD}+ undeclared = sorted(set(polled) - declared)+ (ART / "observed_polls.json").write_text(+ json.dumps(+ {+ "watch_seconds": WATCH_S,+ "threshold": POLL_THRESHOLD,+ "totals": dict(sorted(seen.items())),+ "per_dwell_max": dict(sorted(per_dwell_max.items())),+ "polled": dict(sorted(polled.items())),+ "undeclared": undeclared,+ },+ indent = 2,+ )+ )++ info(+ f"watched {WATCH_S:.0f}s: {len(seen)} distinct API paths, "+ f"{len(polled)} repeated {POLL_THRESHOLD}x or more inside a single dwell"+ )++ if len(polled) < MIN_POLLED_PATHS:+ # Too thin to mean anything: the listener never attached, the walk never left one+ # screen, or the window was too short. A clean sheet from a run like that is not a+ # pass, it is an absence of evidence, so say so instead of reporting green.+ info(+ f"FAIL saw only {len(polled)} polled path(s), expected at least "+ f"{MIN_POLLED_PATHS}; this run cannot vouch for anything"+ )+ for path, n in sorted(polled.items()):+ info(f" {path} {n}x")+ return 1++ # Declared-but-unobserved is NOT a failure. Several entries only poll while a pane is+ # open (the settings dialog, a download, the log viewer), and an idle run legitimately+ # never sees them.+ unobserved = sorted(declared - set(polled))+ if unobserved:+ info(+ f"note: {len(unobserved)} declared polls not seen while idle "+ f"(expected for pane-scoped and busy-only polls)"+ )++ if undeclared:+ info("")+ info("FAIL these paths are polled by the app but are not in the log budget:")+ for path in undeclared:+ per_min = polled[path] * 60.0 / (WATCH_S / (len(SECTIONS) + 1))+ info(f" {path} {polled[path]}x within one dwell (~{per_min:.1f}/min)")+ info("")+ info("Each one needs two lines, in studio/backend/tests/log_budget/session.py:")+ info(" add the path to IDLE_POLLS (or BUSY_POLLS if it only runs during an")+ info(" operation) with the interval its call site declares, and give it a class")+ info(" in studio/backend/loggers/handlers.py. A path left unclassified logs")+ info(" every single hit.")+ return 1++ info("PASS every polled path is declared and classified")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())